package com.net.traffic;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import android.content.Context;
import android.os.FileObserver;

public class MyDataMonitor {
	private static boolean STARTED = false;
	private static FileObserver d;
	private static HashMap<String, Long> transmitted = new HashMap<String, Long>();
	private static HashMap<String, Long> recieved = new HashMap<String, Long>();

	public static synchronized void startMonitoring(Context context) {
		if (STARTED)
			return;
		STARTED = true;
		try {
			d = new DataObserver("/proc/net/dev");
			d.startWatching();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static synchronized void stopMonitoring(Context context) {
		if (!STARTED)
			return;
		try {
			d.stopWatching();
			d = null;
			STARTED = false;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static class DataObserver extends FileObserver {
		public DataObserver(String path) {
			super(path);
			transmit(path);
		}

		@Override
		public void onEvent(int event, String path) {
			transmit(path);
		}

		@Override
		protected void finalize() {
			super.finalize();
		}
	}

	public static void transmit(String path) {
		try {
			InputStream in;
			in = new FileInputStream(new File(path));
			InputStreamReader isr = new InputStreamReader(in);
			char[] inputBuffer = new char[1000];
			isr.read(inputBuffer);
			String data = new String(inputBuffer);
			String[] rows = (data.split("\\n"));
			isr.close();
			in.close();
			// first 2 lines are junk.
			for (int i = 2; i < rows.length; i++) {

				String s = rows[i];
				String[] groups = s.split(":");

				s = groups[1];
				String[] temp = s.split("\\s++");
				if (temp.length != 3) {
					if (recieved.containsKey(temp[0])) {
						recieved.put(groups[0], Long.valueOf(temp[0])
								+ recieved.get(temp[0]));
					} else
						recieved.put(groups[0], Long.valueOf(temp[0]));
					if (transmitted.containsKey(temp[0])) {
						transmitted.put(groups[0], Long.valueOf(temp[0])
								+ transmitted.get(temp[0]));
					} else
						transmitted.put(groups[0], Long.valueOf(temp[0]));

				}

			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
